# 菜品信息管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import Shop,Product,Member,Category
from django.core.paginator import Paginator #导入翻页模块
from datetime import datetime
import time,os
# Create your views here.

def index(request,ccindex=1):
    # 浏览信息
    umod = Member.objects # 获取实例化操作对象
    # userlist=umod.all() #获取遍历对象的信息
    clist = umod.filter(status__lt=9) # 查找除status__lt=9之外的数据

    #获取并判断搜索条件
    mywhere=[]
    kw=request.GET.get("keyword",None) #获取网页上传过来的搜索的值
    if kw:
        clist=clist.filter(name__contains=kw) #__contains 模糊查询,Q表示 或 的条件
        mywhere.append('keyword='+kw)

    #获取并判断搜索菜品类别条件  
    cid=request.GET.get("category_id",None) #获取网页上传过来的搜索的值
    if cid:
        clist=clist.filter(name__contains=cid) #__contains 模糊查询,Q表示 或 的条件
        mywhere.append('category_id='+cid)

    #获取、判断并封装状态status搜索条件
    status = request.GET.get('status','')
    if status != '':
        clist = clist.filter(status=status)
        mywhere.append("status="+status)

    clist = clist.order_by("id") # 对id排序
        
    # 执行分页处理   
    ccindex = int(ccindex)
    page=Paginator(clist,10) #每页的数据条数
    maxppages=page.num_pages # 获取总页数
    
    #判断当前页是否越界    
    if ccindex > maxppages:
        ccindex = maxppages
    if ccindex < 1:
        ccindex = 1
    memberlist = page.page(ccindex) #获取当前页数据
    plist = page.page_range #获取页码列表信息

    contest = {"memberlist":memberlist,'plist':plist,'ccindex':ccindex,'maxppages':maxppages,'mywhere':mywhere} #封装对象的信息
    return render(request,'myadmin/member/index.html',contest) # 把封装的信息加载到模板里面

def add(request):
    '''加载添加信息'''
    # 获取当前所有店铺
    slist = Shop.objects.values("id",'name')
    context = {"shoplist":slist} # 封装
    return render(request,'myadmin/member/add.html',context)

def insert(request):
    # 执行信息添加
    try:
        #会员图片的上传处理
        myfile = request.FILES.get("avatar",None)
        if not myfile:
            return HttpResponse("没有会员图片上传文件信息")
        avatar = str(time.time())+"."+myfile.name.split('.').pop()
        destination = open("./static/uploads/member/"+avatar,"wb+")
        for chunk in myfile.chunks(): # 分块写入文件
            destination.write(chunk)
        destination.close()

        ob = Member()
        ob.nickname = request.POST['nickname']
        ob.mobile = request.POST['mobile']
        ob.avatar = avatar
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d")
        ob.update_at = datetime.now().strftime("%Y-%m-%d")
        ob.save()
        context = {'info':"添加成功！"}
    except Exception as err:
        print(err)
        context = {'info':"添加失败！"}
    return render(request,"myadmin/info.html",context)
def delete(request,pid=0):
    # 执行信息删除
    try:
        ob = Member.objects.get(id=pid) # 获取表单的数据id=uid
        ob.status = 9 # 修改状态
        ob.update_at = datetime.now().strftime("%Y-%m-%d")
        ob.save()
        context = {'info':"删除成功！"}
    except Exception as err:
        print(err)
        context = {'info':"删除失败！"}
    return render(request,"myadmin/info.html",context)

def edit(request,pid=0):
    # 加载信息编辑表单
    try:
        ob = Member.objects.get(id=pid) # 获取表单的数据id=uid\
        context = {'member':ob}
        # 获取当前所有店铺
        slist = Shop.objects.values("id",'name')
        context["shoplist"] = slist # 追加封装
        return render(request,"myadmin/member/edit.html",context)

    except Exception as err:
        print(err)
        context = {'info':"没有找到修改的数据信息"}
        return render(request,"myadmin/info.html",context)

def update(request,pid):
    # 执行信息编辑（修改）
    try:
        #获取原图片
        oldavatar = request.POST['oldavatar']
        #菜品图片的上传处理
        myfile = request.FILES.get("avatar",None)
        if not myfile:
            avatar = oldavatar
        else:
            avatar = str(time.time())+"."+myfile.name.split('.').pop()
            destination = open("./static/uploads/member/"+avatar,"wb+")
            for chunk in myfile.chunks(): # 分块写入文件
                destination.write(chunk)
            destination.close()

        ob = Member.objects.get(id=pid) # 获取表单的数据id=uid
        ob.nickname = request.POST['nickname']
        ob.mobile = request.POST['mobile']
        ob.avatar = avatar
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d")
        ob.save()
        context = {'info':"修改成功！"}
        
        #判断并删除老图片
        if myfile:
            os.remove("./static/uploads/member/"+oldavatar)

    except Exception as err:
        print(err)
        context = {'info':"修改失败！"}
        #判断并删除新图片
        if myfile:
            os.remove("./static/uploads/member/"+avatar)
    return render(request,"myadmin/info.html",context)
